package com.ruoyi.system.controller;

import java.io.File;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.swing.clipboard.ClipboardUtil;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.OrderList;
import com.ruoyi.system.domain.ProfitJifen;
import com.ruoyi.system.dto.SumUser;
import com.ruoyi.system.dto.UserBagTopDTO;
import com.ruoyi.system.dto.UserYkDTO;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.util.MultipartFileToFile;
import com.ruoyi.system.util.UpFileUtils;
import io.swagger.models.auth.In;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Admin;
import com.ruoyi.system.service.IAdminService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【管理员】Controller
 *
 * @author ruoyi
 * @date 2022-05-24
 */
@RestController
@RequestMapping("/system/admin")
public class AdminController extends BaseController
{
    @Autowired
    private IAdminService adminService;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private InfiniteGoodsMapper infiniteGoodsMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private OrderListMapper orderListMapper;

    @Resource
    private ProfitMoneyMapper profitMoneyMapper;

    @Resource
    private ProfitJifenMapper profitJifenMapper;



    @GetMapping("/userBagTop")
    public AjaxResult userBagTop()
    {
        List<UserBagTopDTO> userBagTopDTOS = userMapper.selectUserBagTop();

        return AjaxResult.success(userBagTopDTOS);
    }


    @PostMapping("/userTotalXfPh")
    public AjaxResult userTotalXfPh(@RequestParam(value = "start",required = false)String start,
                                    @RequestParam(value = "end",required = false)String end)
    {
         logger.info("startTime: {},endTime：{}",start,end);
         if(!StringUtils.isEmpty(start)&&!StringUtils.isEmpty(end))
         {
             List<SumUser> sumUser = profitMoneyMapper.userTotalXfPh(start,end);
             return AjaxResult.success(sumUser);
         }
         start= "2000-07-19 00:15:19";
         end="2050-07-19 00:15:19";

         List<SumUser> sumUser = profitMoneyMapper.userTotalXfPh(start,end);
        return AjaxResult.success(sumUser);

    }


    @PostMapping("/userYk")
    public AjaxResult userYk(@RequestBody UserYkDTO userYkDTO)
    {
        BigDecimal sum = orderListMapper.selectSumByStartAndEndAndUserId(userYkDTO);


        return AjaxResult.success(sum);
    }



    @PostMapping("/yfsYk") //一番赏盈亏
    public AjaxResult yfsYk(@RequestParam("start")String start,@RequestParam("end")String end)
    {

       List<OrderList> orderLists = orderListMapper.selectYFSYKByTime(start,end);

        AtomicReference<BigDecimal> outPrice= new AtomicReference<>(new BigDecimal(0));
        AtomicReference<BigDecimal> price = new AtomicReference<>(new BigDecimal(0));
       orderLists.forEach(
               o->{
                   outPrice.set(outPrice.get().add(o.getOutPrice()));
                   price.set(price.get().add(o.getPrice()));
               }
       );
        BigDecimal yfsYk = price.get().subtract(outPrice.get());
        return AjaxResult.success("一番赏盈亏",yfsYk);
    }

    @PostMapping("/wxsYk")//无限赏盈亏
    public AjaxResult wxsYk()
    {
        BigDecimal wxsYk;
        BigDecimal bigDecimal = infiniteGoodsMapper.selectAllMenkan();
        BigDecimal bigDecimal1 = infiniteGoodsMapper.selectProfit();

        wxsYk = bigDecimal.add(bigDecimal1);



        return AjaxResult.success("无限赏盈亏",wxsYk);
    }


    @PostMapping("/whetherPrivilegeStatistics")
    public AjaxResult whetherPrivilegeStatistics(@RequestParam("type")Integer ifPrivate)
    {
        BigDecimal backpack = new BigDecimal(0);
        BigDecimal add1 = orderListMapper.selectYfsAll(ifPrivate);
        if(add1==null)
        {
            add1=new BigDecimal(0);
        }
        BigDecimal add2 = orderListMapper.selectWxssAll(ifPrivate);
        if(add2==null)
        {
            add2=new BigDecimal(0);
        }
        BigDecimal add3 = orderListMapper.selectFpAll(ifPrivate);
        if(add3==null)
        {
            add3=new BigDecimal(0);
        }
        backpack = add1.add(add2).add(add3);


        BigDecimal userYue = userMapper.selectUserCountMoneyV2(ifPrivate);
        Integer mb = userMapper.selectMbProfitV2(ifPrivate);
        Integer jf = userMapper.selectJfProfitV2(ifPrivate);

        Integer countUser = userMapper.selectUserCountV2(ifPrivate);
        Integer todayCount = userMapper.selectTodayCountV2(DateUtil.beginOfDay(new Date()),DateUtil.endOfDay(new Date()),ifPrivate);




        return AjaxResult.success(MapUtil.builder()
                        .put("backpack",backpack)
                        .put("userYue",userYue)
                        .put("mb",mb)
                        .put("jf",jf)
                        .put("countUser",countUser)
                        .put("todayCount",todayCount)
                        .build()
                );
    }


    @PostMapping("/ptxf")
    public AjaxResult ptxf()
    {

        /**
         *   无限赏与普通赏的区别在
         *   luckno是否为0 为0 则是一番赏 无限赏又不 在这里算 所以直接计算 当前的luckno为0即可
         */


        //用户订单总金额
      //普通抽奖 无限抽奖
       BigDecimal count =  orderMapper.selectProfit();

       //无限抽奖
       // (回收)普通抽奖 无限抽奖
       BigDecimal count2 =  orderMapper.selectProfit2();

       BigDecimal wxYingLi = infiniteGoodsMapper.selectProfit(); //无限赏总抽成
        //奖池总金额
        BigDecimal jiangChi = infiniteGoodsMapper.selectAllMenkan();

        // 统计用户(背包+保险柜)内物品总价值
        BigDecimal backpack = orderListMapper.selectAllBackpack();

        //当前套数卖完之后统计商品总回收价 - 票价 得到盈亏


       BigDecimal mb = userMapper.selectMbProfit();

       BigDecimal userJf = userMapper.selectJfProfit();

        BigDecimal jfCj =orderMapper.selectJfProfit();
        if(jfCj!=null)
        {
            jfCj= jfCj.divide(new BigDecimal(100));
        }else {
            jfCj=new BigDecimal(0);
        }
        if(count==null)
        {
            count=new BigDecimal(0);
        }
        if(count2==null)
        {
            count2=new BigDecimal(0);
        }
        if(wxYingLi==null)
        {
            wxYingLi=new BigDecimal(0);
        }
        if (userJf==null)
        {
            userJf=new BigDecimal(0);
        }
        if(mb==null)
        {
            mb=new BigDecimal(0);
        }

        BigDecimal yk = new BigDecimal(0);


        return AjaxResult.success(MapUtil.builder()
                .put("无限池奖池总奖金",jiangChi)
                .put("用户背包和保险柜总金额",backpack)
                .put("普通消费",count)
                .put("普通回收",count2)
                .put("无限赏抽成",wxYingLi)
                .put("M币总余额",mb)
                .put("用户总积分",userJf)
                .put("积分消费",jfCj.multiply(new BigDecimal(100)))
                .put("盈亏",yk).build()
        );
    }



    /**
     *
     * @param files
     * @return
     * @throws Exception
     */
    @PreAuthorize("@ss.hasPermi('system:admin:uploadFile')")
    @PostMapping("/uploadFile")
    @RepeatSubmit
    public AjaxResult uploadFile(@RequestParam("files") MultipartFile[] files) throws Exception {
        List urlList =new ArrayList();

        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                return AjaxResult.error("文件不能为空");
            }
            String fileName = LocalDateTime.now().toString()+".jpg";
            logger.info("当前时间"+System.currentTimeMillis());

            File temp = MultipartFileToFile.multipartFileToFile(file);

            UpFileUtils up =new UpFileUtils();
            int responseCode = up.up(temp,fileName);
            //然后删除本地头像
            MultipartFileToFile.delteTempFile(temp);
            String imgUrl = "";
            if(responseCode==200)
            {
                imgUrl="https://manoushang.flya.top/file/"+fileName;
                urlList.add(imgUrl);
            }
        }


        return AjaxResult.success(urlList);
    }


    /**
     * 查询【管理员列表】列表
     */
    @PreAuthorize("@ss.hasPermi('system:admin:list')")
    @GetMapping("/list")
    public TableDataInfo list(Admin admin)
    {
        startPage();
        List<Admin> list = adminService.selectAdminList(admin);
        return getDataTable(list);
    }

    /**
     * 导出【管理员】列表
     */
    @PreAuthorize("@ss.hasPermi('system:admin:export')")
    @Log(title = "【管理员】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Admin admin)
    {
        List<Admin> list = adminService.selectAdminList(admin);
        ExcelUtil<Admin> util = new ExcelUtil<Admin>(Admin.class);
        util.exportExcel(response, list, "【管理员】数据");
    }

    /**
     * 获取【管理员】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:admin:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(adminService.selectAdminById(id));
    }

    /**
     * 新增【管理员】
     */
    @PreAuthorize("@ss.hasPermi('system:admin:add')")
    @Log(title = "【管理员】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Admin admin)
    {
        return toAjax(adminService.insertAdmin(admin));
    }

    /**
     * 修改【管理员】
     */
    @PreAuthorize("@ss.hasPermi('system:admin:edit')")
    @Log(title = "【管理员】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Admin admin)
    {
        return toAjax(adminService.updateAdmin(admin));
    }

    /**
     * 删除【管理员】
     */
    @PreAuthorize("@ss.hasPermi('system:admin:remove')")
    @Log(title = "【管理员】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(adminService.deleteAdminByIds(ids));
    }
}
